package com.time.company.components.discovery;

import android.annotation.SuppressLint;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.andview.refreshview.XRefreshView;
import com.google.gson.Gson;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseXRecAdapter;
import com.time.company.components.WebDetailActivity;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.discovery.Discovery;
import com.time.company.servermodel.discovery.DiscoveryList;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.views.CustomHeaderView;
import com.time.company.views.CustomerFooter;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.DiscoveryParameters;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bing on 2017/10/25.
 * E-mail is tx16bing@163.com
 */

@SuppressLint("ValidFragment")
public class CollectionFrag extends BaseDisFragment {

    private String mFlag;

    private LinearLayout llEmpty;
    private XRefreshView xRefreshView;
    private RecyclerView rvCollection;
    private CollAdapter collAdapter;
    private List<Discovery> discoveries;

    private Request request;
    private static final int RECRUITING_WHAT = 40;
    private static final int RECRUITING_LOAD_WHAT = 41;

    public CollectionFrag() {

    }

    public CollectionFrag(String flag) {
        mFlag = flag;
    }

    @Override
    public void initContentView(View contentView) {
        assignViews();
        if (!TextUtils.isEmpty(DiscoveryFragment.CURRENT_CITY)) {
            recruitingRequest(getString(R.string.zero), RECRUITING_WHAT);
        }
    }

    private void assignViews() {
        llEmpty = findView(R.id.ll_no_result);
        xRefreshView = findView(R.id.collection_refresh);
        rvCollection = findView(R.id.rv_collection);
        LinearLayoutManager lm = new LinearLayoutManager(mContext);
        lm.setOrientation(LinearLayoutManager.VERTICAL);
        rvCollection.setHasFixedSize(true);
        rvCollection.setNestedScrollingEnabled(false);
        rvCollection.setLayoutManager(lm);
        rvCollection.setItemAnimator(new DefaultItemAnimator());

        xRefreshView.setPinnedTime(1000);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setAutoLoadMore(false);
        xRefreshView.setCustomHeaderView(new CustomHeaderView(mContext, 1000));
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPull) {
                // Noting to do
                recruitingRequest(getString(R.string.zero), RECRUITING_WHAT);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                if (discoveries != null && !discoveries.isEmpty()) {
                    String loadId = discoveries.get(discoveries.size() - 1).getId();
                    Logger.i("Load id " + loadId);
                    recruitingRequest(loadId + "", RECRUITING_LOAD_WHAT);
                }
            }
        });
        xRefreshView.setHideFooterWhenComplete(true);
    }

    @Override
    public int bindLayoutId() {
        return R.layout.fragment_collection;
    }

    @Override
    public void refreshData() {
        super.refreshData();
        recruitingRequest(getString(R.string.zero), RECRUITING_WHAT);
    }

    private void recruitingRequest(String id, int what) {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            DiscoveryParameters parameters = new DiscoveryParameters();
            parameters.setCommand(application.getString(R.string.command_getFindPublicGoodList));
            parameters.setUserId(application.getAccount());
            parameters.setActId(id);
            parameters.setState(getString(R.string.dis_recruiting));
            parameters.setCity(DiscoveryFragment.CURRENT_CITY);
            request.add(application.getString(R.string.command), parameters.getCommand());
            request.add(application.getString(R.string.platform), parameters.getPlatform());
            request.add(application.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(mContext, request, this,
                    what, true, true, true);
        } else {
            ToastUtils.showShort(application.getString(R.string.network_error));
        }
    }

    private void setDisAdapter() {
        bindEmpty();
        if (collAdapter == null) {
            collAdapter = new CollAdapter(mContext, discoveries, 1);
            collAdapter.setOnItemClickListener(new BaseXRecAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, Object o, int type) {
                    // 公益详情
                    if (o instanceof Discovery) {
                        Discovery discovery = (Discovery) o;
                        String url = new StringBuilder()
                                .append(DiscoveryFragment.detailUrl)
                                .append(discovery.getId())
                                .toString();
                        WebDetailActivity.start(mContext,
                                application.getString(R.string.dynamics_details),
                                url);
                    }
                }
            });
            rvCollection.setAdapter(collAdapter);
        } else {
            collAdapter.updateData(this.discoveries);
        }

        if (discoveries.size() >= 10) {
            CustomerFooter customerFooter = new CustomerFooter(mContext);
            customerFooter.setRecyclerView(rvCollection);
            customerFooter.callWhenNotAutoLoadMore(xRefreshView);
            collAdapter.setCustomLoadMoreView(customerFooter);
        }
    }

    private void bindEmpty(){
        if (this.discoveries.isEmpty()){
            llEmpty.setVisibility(View.VISIBLE);
            xRefreshView.setVisibility(View.GONE);
        }else {
            llEmpty.setVisibility(View.GONE);
            xRefreshView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;
        if (basicBean.isSuccess()) {
            if (what == RECRUITING_WHAT) {
                DiscoveryList list = basicBean.parseData(DiscoveryList.class);
                if (list == null) return;
                ArrayList<Discovery> discoveries = list.getDiscoveries();
                if (discoveries == null) return;

                this.discoveries = discoveries;
                setDisAdapter();
            } else {
                DiscoveryList list = basicBean.parseData(DiscoveryList.class);
                if (list == null) return;
                ArrayList<Discovery> discoveries = list.getDiscoveries();
                if (discoveries == null) return;
                this.discoveries.addAll(discoveries);
                setDisAdapter();
            }
            endRequest();
        } else if (basicBean.isNothing()) {
            if (what == RECRUITING_WHAT) {
                this.discoveries = new ArrayList<>();
                setDisAdapter();
            } else if (what == RECRUITING_LOAD_WHAT) {
                ToastUtils.showShort(basicBean.getMsg());
            }
            endRequest();
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    private void endRequest() {
        endRefreshing();
        endLoading();
    }

    private void endRefreshing() {
        xRefreshView.stopRefresh();
    }

    private void endLoading() {
        xRefreshView.stopLoadMore();
    }
}
